package lar.system.network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import lar.system.engine.MainProgram;

import android.content.Context;
import android.net.DhcpInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

public class UDPBroadcaster 
{
	private int port;
	private DatagramSocket outSocket;
	private InetAddress broadcastAddress;
	
	public UDPBroadcaster(int port) throws IOException
	{
		outSocket = new DatagramSocket(port);
        outSocket.setBroadcast(true);
        outSocket.setReuseAddress(false);
        broadcastAddress = getBroadcastAddress();
	}
	
	public UDPBroadcaster() throws IOException
	{
		outSocket = new DatagramSocket();
        outSocket.setBroadcast(true);
        outSocket.setReuseAddress(false);
        broadcastAddress = getBroadcastAddress();
	}

	
	public void shutDown()
	{
		if(outSocket == null) return;
		outSocket.close();
		outSocket = null;
	}
	
	public void sendBroadcast(String msg)
	{
		if(outSocket == null) return;
		DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(), msg.length(), broadcastAddress, 8000);
        try 
        {
			outSocket.send(datagramPacket);
			//Log.d("R", "Sent Broadcast: " + msg);
        } catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static InetAddress getBroadcastAddress() throws IOException 
	{
	     WifiManager wifi = (WifiManager) MainProgram.currentActivity.getSystemService(Context.WIFI_SERVICE);
	     DhcpInfo dhcp = wifi.getDhcpInfo();
	     // handle null somehow

	     int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
	     byte[] quads = new byte[4];
	     for (int k = 0; k < 4; k++)
	       quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
	     return InetAddress.getByAddress(quads);
	 }

}
